<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\TeachingPlan;
use app\model\TeachingPlanElement;
use think\facade\Db;

class TeachingPlanController extends BaseController
{
    /**
     * 教案列表
     */
    public function index(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);
        $noteId = $request->param('note_id');

        $query = TeachingPlan::where('user_id', $user->id);
        
        if (!empty($noteId)) {
            $query->where('note_id', $noteId);
        }

        $plans = $query->with(['note'])
            ->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        // 获取每个教案的AI角色信息
        $formattedPlans = array_map(function($plan) {
            $data = $plan->toArray();
            if ($plan->ai_roles_id > 0) {
                $data['ai_role'] = Db::name('ai_roles')
                    ->where('id', $plan->ai_roles_id)
                    ->field('id,name,avatar,description')
                    ->find();
            } else {
                $data['ai_role'] = null;
            }
            return $data;
        }, $plans->items());

        return json([
            'status' => 200,
            'data' => [
                'total' => $plans->total(),
                'current_page' => $plans->currentPage(),
                'last_page' => $plans->lastPage(),
                'plans' => $formattedPlans
            ]
        ]);
    }

    /**
     * 创建教案
     */
    public function create(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['title']) || empty($data['note_id'])) {
            return json(['status' => 400, 'message' => '请填写教案标题和关联笔记']);
        }

        Db::startTrans();
        try {
            $plan = new TeachingPlan;
            $plan->user_id = $user->id;
            $plan->note_id = $data['note_id'];
            $plan->title = $data['title'];
            $plan->description = $data['description'] ?? '';
            $plan->ai_roles_id = $data['ai_roles_id'] ?? 0;
            $plan->save();

            // 如果有初始元素，创建元素
            if (!empty($data['elements'])) {
                foreach ($data['elements'] as $index => $element) {
                    $this->createElement($plan->id, $element, $index);
                }
                
                // 更新教案的元素统计
                $this->updatePlanElementCounts($plan->id);
            }

            Db::commit();
            return json([
                'status' => 200,
                'message' => '教案创建成功',
                'data' => $plan
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新教案基本信息
     */
    public function update(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $planId = $request->param('id');
        $data = $request->post();

        $plan = TeachingPlan::where('id', $planId)
            ->where('user_id', $user->id)
            ->find();

        if (!$plan) {
            return json(['status' => 404, 'message' => '教案不存在或无权限']);
        }

        try {
            $plan->title = $data['title'] ?? $plan->title;
            $plan->description = $data['description'] ?? $plan->description;
            if (isset($data['ai_roles_id'])) {
                $plan->ai_roles_id = $data['ai_roles_id'];
            }
            $plan->save();

            return json(['status' => 200, 'message' => '更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除教案
     */
    public function delete(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $planId = $request->param('id');

        $plan = TeachingPlan::where('id', $planId)
            ->where('user_id', $user->id)
            ->find();

        if (!$plan) {
            return json(['status' => 404, 'message' => '教案不存在或无权限']);
        }

        Db::startTrans();
        try {
            // 删除所有相关元素
            TeachingPlanElement::where('plan_id', $planId)->delete();
            // 删除教案
            $plan->delete();

            Db::commit();
            return json(['status' => 200, 'message' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取教案详情
     */
    public function detail(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $planId = $request->param('id');
        
        try {
            $plan = TeachingPlan::with(['elements' => function($query) {
                    $query->order('sort_order', 'asc');
                }])
                ->where('id', $planId)
                ->where('user_id', $user->id)
                ->find();

            if (!$plan) {
                return json(['status' => 404, 'message' => '教案不存在']);
            }

            $data = $plan->toArray();
            
            // 获取AI角色信息
            if ($plan->ai_roles_id > 0) {
                $data['ai_role'] = Db::name('ai_roles')
                    ->where('id', $plan->ai_roles_id)
                    ->field('id,name,avatar,description')
                    ->find();
            } else {
                $data['ai_role'] = null;
            }

            return json([
                'status' => 200,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '获取失败：' . $e->getMessage()]);
        }
    }

    /**
     * 添加教案元素
     */
    public function addElement(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $planId = $request->param('plan_id');
        $data = $request->post();

        $plan = TeachingPlan::where('id', $planId)
            ->where('user_id', $user->id)
            ->find();

        if (!$plan) {
            return json(['status' => 404, 'message' => '教案不存在或无权限']);
        }

        Db::startTrans();
        try {
            // 获取当前最大排序号
            $maxSort = TeachingPlanElement::where('plan_id', $planId)->max('sort_order');
            $data['sort_order'] = $maxSort + 1;
            
            $element = $this->createElement($planId, $data);
            
            // 更新教案的元素统计
            $this->updatePlanElementCounts($planId);

            Db::commit();
            return json([
                'status' => 200,
                'message' => '添加成功',
                'data' => $element
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '添加失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新教案元素
     */
    public function updateElement(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $elementId = $request->param('id');
        $data = $request->post();

        $element = TeachingPlanElement::with(['teachingPlan'])
            ->where('id', $elementId)
            ->find();

        if (!$element || $element->teachingPlan->user_id !== $user->id) {
            return json(['status' => 404, 'message' => '元素不存在或无权限']);
        }

        try {
            $element->save($data);
            return json(['status' => 200, 'message' => '更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除教案元素
     */
    public function deleteElement(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $elementId = $request->param('id');

        $element = TeachingPlanElement::with(['teachingPlan'])
            ->where('id', $elementId)
            ->find();

        if (!$element || $element->teachingPlan->user_id !== $user->id) {
            return json(['status' => 404, 'message' => '元素不存在或无权限']);
        }

        Db::startTrans();
        try {
            $element->delete();
            
            // 更新教案的元素统计
            $this->updatePlanElementCounts($element->plan_id);

            Db::commit();
            return json(['status' => 200, 'message' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新元素排序
     */
    public function updateElementSort(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $planId = $request->param('plan_id');
        $sortData = $request->post('sort_data'); // 格式：[{id: 1, sort_order: 1}, ...]

        $plan = TeachingPlan::where('id', $planId)
            ->where('user_id', $user->id)
            ->find();

        if (!$plan) {
            return json(['status' => 404, 'message' => '教案不存在或无权限']);
        }

        Db::startTrans();
        try {
            foreach ($sortData as $item) {
                TeachingPlanElement::where('id', $item['id'])
                    ->where('plan_id', $planId)
                    ->update(['sort_order' => $item['sort_order']]);
            }

            Db::commit();
            return json(['status' => 200, 'message' => '排序更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '排序更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 创建教案元素
     */
    private function createElement($planId, $data, $sortOrder = 0)
    {
        $element = new TeachingPlanElement;
        $element->plan_id = $planId;
        $element->type = $data['type'];
        $element->point = $data['point'];
        $element->content = $data['content'] ?? '';
        $element->extra_data = $data['extra_data'] ?? null;
        $element->sort_order = $data['sort_order'] ?? $sortOrder;

        if ($data['type'] === TeachingPlanElement::TYPE_QUESTION) {
            $element->answer = $data['answer'] ?? '';
            $element->score = $data['score'] ?? 0;
            $element->passing_score = $data['passing_score'] ?? 0;
        }

        $element->save();
        return $element;
    }

    /**
     * 更新教案的元素统计
     */
    private function updatePlanElementCounts($planId)
    {
        $lectureCount = TeachingPlanElement::where('plan_id', $planId)
            ->where('type', TeachingPlanElement::TYPE_LECTURE)
            ->count();
            
        $questionCount = TeachingPlanElement::where('plan_id', $planId)
            ->where('type', TeachingPlanElement::TYPE_QUESTION)
            ->count();

        TeachingPlan::where('id', $planId)->update([
            'lecture_count' => $lectureCount,
            'question_count' => $questionCount,
            'total_elements' => $lectureCount + $questionCount
        ]);
    }
} 